package com.xiuxia.bopicturebackend.manager.websocket.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xiuxia.bopicturebackend.manager.auth.SpaceUserAuthManager;
import com.xiuxia.bopicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.xiuxia.bopicturebackend.model.entity.Picture;
import com.xiuxia.bopicturebackend.model.entity.Space;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.enums.SpaceTypeEnum;
import com.xiuxia.bopicturebackend.service.PictureService;
import com.xiuxia.bopicturebackend.service.SpaceService;
import com.xiuxia.bopicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName WebSocketHandshakeInterceptor
 * @Author CHENBO
 * @Date 2025/7/29 11:10
 * 拦截器，用于拦截WebSocket请求，验证用户权限
 */
@Component
@Slf4j
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 建立连接之前
     *
     * @param request    请求
     * @param response   响应
     * @param wsHandler  处理器
     * @param attributes 属性
     * @return true：握手成功，false：握手失败
     * @throws Exception 抛出异常
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 获取请求参数
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("WebSocketHandshakeInterceptor|beforeHandshake|缺少pictureId，拒绝握手");
                return false;
            }
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (Objects.isNull(loginUser)) {
                log.error("WebSocketHandshakeInterceptor|beforeHandshake|未登录，拒绝握手");
                return false;
            }
            // 检验用户是否拥有该图片的编辑权限
            Picture picture = pictureService.getById(pictureId);
            if (picture == null) {
                log.error("WebSocketHandshakeInterceptor|beforeHandshake|图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if (spaceId != null) {
                space = spaceService.getById(spaceId);
                if (space == null) {
                    log.error("WebSocketHandshakeInterceptor|beforeHandshake|空间不存在，拒绝握手");
                    return false;
                }
                if (space.getSpaceType() != SpaceTypeEnum.TEAM.getValue()) {
                    log.error("WebSocketHandshakeInterceptor|beforeHandshake|非团队空间，拒绝握手");
                    return false;
                }
            }
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("WebSocketHandshakeInterceptor|beforeHandshake|用户没有该图片的编辑权限，拒绝握手");
                return false;
            }
            attributes.put("user", loginUser);
            attributes.put("pictureId", Long.valueOf(pictureId));
            attributes.put("userId", loginUser.getId());
        }
        return true;
    }

    /**
     * 建立连接之后
     *
     * @param request   请求
     * @param response  响应
     * @param wsHandler 处理器
     * @param exception 异常
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
